package com.tsfyun.scm.system.service.impl;

import com.google.common.collect.Lists;
import com.tsfyun.common.base.constant.CacheConstant;
import com.tsfyun.scm.system.dto.DistrictNameDto;
import com.tsfyun.scm.system.mapper.DistrictMapper;
import com.tsfyun.scm.system.service.IDistrictService;
import com.tsfyun.scm.system.vo.SimpleDistrictVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class DistrictServiceImpl implements IDistrictService {

    @Autowired
    private DistrictMapper districtMapper;


    @Override
    public List<DistrictNameDto> findAllProvince() {
        return districtMapper.findAllProvince();
    }

    @Override
    public List<DistrictNameDto> findCityByProvince(String pname) {
        return districtMapper.findCityByProvince(pname);
    }

    @Override
    public List<DistrictNameDto> findAreaByProvinceAndCity(String pname, String cname) {
        return districtMapper.findAreaByProvinceAndCity(pname, cname);
    }

    @Override
    @Cacheable(value = CacheConstant.ALL_DISTRICT)
    public List<SimpleDistrictVO> findAll() {
        List<SimpleDistrictVO> list = new ArrayList<>();
        List<DistrictNameDto> provinces = findAllProvince();
        provinces.stream().forEach(p -> {
            List<SimpleDistrictVO> pList = Lists.newArrayList();
            List<DistrictNameDto> citys = districtMapper.findCityByProvince(p.getName());

            citys.stream().forEach(c -> {
                List<SimpleDistrictVO> cList = Lists.newArrayList();
                List<DistrictNameDto> areas = districtMapper.findAreaByProvinceAndCity(p.getName(), c.getName());
                areas.stream().forEach(a -> {
                    SimpleDistrictVO avo = new SimpleDistrictVO();
                    avo.setValue(a.getCode());
                    avo.setLabel(a.getName());
                    cList.add(avo);
                });
                SimpleDistrictVO cvo = new SimpleDistrictVO();
                cvo.setValue(c.getCode());
                cvo.setLabel(c.getName());
                cvo.setChildren(cList);
                pList.add(cvo);
            });
            SimpleDistrictVO pvo = new SimpleDistrictVO();
            pvo.setValue(p.getCode());
            pvo.setLabel(p.getName());
            pvo.setChildren(pList);
            list.add(pvo);
        });
        return list;
    }
}
